<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <div>
          <!-- 搜索表单 -->
          <el-form :model="contractQuery" label-width="auto">
            <div class="form-row">
              <el-form-item label="项目类型">
                <el-select
                  v-model="contractQuery.PType"
                  clearable
                  style="width: 177px"
                  placeholder="请选择项目类型"
                  @change="handleProjectTypeChange"
                >
                  <el-option label="传媒中心" value="传媒中心" />
                  <el-option label="仑传公司" value="仑传公司" />
                </el-select>
              </el-form-item>
              <el-form-item label="项目名称">
                <el-input
                  v-model="contractQuery.PName"
                  style="width: 177px"
                  clearable
                  placeholder="请输入项目名称"
                />
              </el-form-item>
              <el-form-item label="客户单位">
                <el-input
                  v-model="contractQuery.customer"
                  style="width: 177px"
                  clearable
                  placeholder="请输入客户单位"
                />
                <!-- <el-select
                  @change="handleCustomerChange"
                  clearable
                  v-model="contractQuery.customer"
                  placeholder="请选择客户单位"
                  style="width: 177px"
                >
                  <el-option
                    :label="item.name"
                    :value="item.name"
                    v-for="item in customerUnits"
                    :key="item.id"
                  ></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="合同编号">
                <el-input
                  v-model="contractQuery.no"
                  clearable
                  style="width: 177px"
                  placeholder="请输入合同编号"
                />
              </el-form-item>
              <el-form-item label="合同金额">
                <el-input
                  v-model="contractQuery.money"
                  clearable
                  style="width: 177px"
                  placeholder="请输入合同金额"
                />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="项目内容">
                <el-input
                  v-model="contractQuery.content"
                  clearable
                  style="width: 177px"
                  placeholder="请输入项目内容"
                />
              </el-form-item>
              <el-form-item label="立项时间">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleDateChange"
                />
              </el-form-item>
              <el-form-item label="项目负责人">
                <el-input
                  v-model="contractQuery.salesman"
                  clearable
                  style="width: 177px"
                  placeholder="请输入负责人姓名"
                />
              </el-form-item>
              <el-form-item label="单据状态">
                <el-select
                  v-model="contractQuery.status"
                  clearable
                  placeholder="请选择单据状态"
                  style="width: 177px"
                  @change="handleStatusChange"
                >
                  <el-option
                    v-for="item in statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
              >搜索</el-button>
              <el-button
                icon="el-icon-refresh"
                @click="resetQuery"
              >重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>
    <el-card>
      <!-- 顶部操作按钮 -->
      <div class="operation-container">
        <el-button
          type="primary"
          size="small"
          class="filter-trigger"
          @click="isFilterVisible = !isFilterVisible"
        >{{ isFilterVisible ? "收起" : "检索" }}
          <i
            :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
          />
        </el-button>
        <el-button
          v-if="isAdministrators"
          type="warning"
          icon="el-icon-edit"
          size="small"
          @click="handleEdit"
        >修改</el-button>
        <el-button
          v-if="isAdministrators"
          type="danger"
          icon="el-icon-delete"
          size="small"
          @click="handleDeleteSelected"
        >批量删除</el-button>
        <div style="float: right">
          <el-dropdown @command="handleExportExcel">
            <el-button
              type="primary"
              size="small"
            >导入/导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>excel导出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button
            type="primary"
            icon="el-icon-printer"
            size="small"
            @click="handlePrint"
            >预览/打印</el-button
          > -->
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="contractList"
        border
        style="width: 100%"
        max-height="600px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="no"
          label="合同编号"
          width="120"
          align="center"
        />
        <el-table-column
          min-width="200"
          prop="pname"
          label="项目名称"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="customer"
          label="客户单位"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="customerType"
          label="客户类型"
          width="100"
          align="center"
        />
        <el-table-column
          prop="money"
          label="合同金额"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.money || "0" }}
          </template>
        </el-table-column>
        <el-table-column prop="salesman" label="项目负责人" width="100" />
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="180"
        >
          <template slot-scope="scope">
            {{ formatCreateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="项目状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="getProjectStatusType(scope.row.status)">{{
              getProjectStatus(scope.row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleView(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 20px" type="flex" justify="end">
        <el-pagination
          background
          :current-page="contractQuery.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="contractQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 修改弹框 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="87%">
      <el-form
        ref="editFormRef"
        :model="selectionRow"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目类型" prop="ptype">
              <el-select
                v-model="selectionRow.ptype"
                placeholder="请选择项目类型"
                style="width: 100%"
              >
                <el-option label="传媒中心" value="传媒中心" />
                <el-option label="仑传公司" value="仑传公司" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目采购方式" prop="projectFrom">
              <el-select
                v-model="selectionRow.projectFrom"
                placeholder="请选择项目采购方式"
                style="width: 100%"
              >
                <el-option
                  v-for="item in projectFroms"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="no">
              <el-input
                v-model="selectionRow.no"
                style="width: 100%"
                placeholder="请输入合同编号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="pname" required>
              <el-input
                v-model="selectionRow.pname"
                style="width: 100%"
                placeholder="请输入项目名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户类型" prop="customerType" required>
              <el-select
                v-model="selectionRow.customerType"
                clearable
                style="width: 100%"
                placeholder="请选择客户类型"
              >
                <el-option
                  v-for="item in projectTypes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户单位" prop="customer" required>
              <!-- <el-select
                v-model="selectionRow.customer"
                placeholder="请选择客户单位"
                style="width: 100%"
              >
                <el-option
                  v-for="item in customerUnits"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select> -->
              <el-input
                v-model="selectionRow.customer"
                style="width: 100%"
                placeholder="请输入客户单位"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="金额" prop="money">
              <el-input
                v-model.number="selectionRow.money"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行时间" prop="duration">
              <el-date-picker
                v-model="selectionRow.duration"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                @change="handleEditDurationChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目领域" prop="projectArea">
              <el-select
                v-model="selectionRow.projectArea"
                placeholder="请选择项目领域"
                style="width: 100%"
              >
                <el-option
                  v-for="item in projectAreas"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存量类型" prop="stockType" required>
              <el-select
                v-model="selectionRow.stockType"
                placeholder="请选择存量类型"
                style="width: 100%"
              >
                <el-option label="存量" value="存量" />
                <el-option label="增量" value="增量" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="salesman" required>
              <el-input
                v-model="selectionRow.salesman"
                style="width: 100%"
                placeholder="请输入项目负责人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目奖励" prop="manageRate">
              <el-select
                ref="editManageRateSelect"
                v-model="selectionRow.manageRate"
                clearable
                filterable
                allow-create
                default-first-option
                style="width: 100%"
                @blur="handleEditManageRateBlur"
                @change="handleEditManageRateChange"
              >
                <el-option
                  v-for="item in manageRateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="内容及要求" prop="content" required>
          <el-input
            v-model="selectionRow.content"
            type="textarea"
            :rows="4"
            placeholder="请输入内容及要求"
          />
        </el-form-item>
        <el-divider />

        <!-- 项目类型表格 -->
        <div class="project-type-section">
          <div class="section-title">项目类型</div>
          <el-table :data="selectionRow.lppStr" border style="width: 100%">
            <el-table-column
              label="平台产品IP"
              prop="platform"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <!-- <el-input v-model="scope.row.platform"></el-input> -->
                <el-select
                  v-model="scope.row.platform"
                  placeholder="请选择平台"
                >
                  <el-option
                    v-for="item in selPlatformLists"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="执行事业部"
              prop="department"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <!-- <el-input v-model="scope.row.department"></el-input> -->
                <el-select
                  v-model="scope.row.department"
                  placeholder="请选择执行事业部"
                >
                  <el-option
                    v-for="item in selDepartmentLists"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="执行内容及要求"
              prop="content"
              width="300"
              align="center"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.content"
                  type="textarea"
                  :rows="4"
                />
              </template>
            </el-table-column>
            <el-table-column label="属性" prop="attribute" align="center">
              <template slot-scope="scope">
                <!-- <el-input v-model="scope.row.attribute"></el-input> -->
                <el-select
                  v-model="scope.row.attribute"
                  placeholder="请选择属性"
                >
                  <el-option
                    v-for="item in selProjectTypeLists"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="金额"
              prop="money"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input
                  v-model.number="scope.row.money"
                  placeholder="请输入金额"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="成本"
              prop="estimatedCost"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-input
                  v-model.number="scope.row.estimatedCost"
                  placeholder="请输入成本"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90" align="center">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="mini"
                  @click="removeEditProjectType(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px">
            <el-button
              type="primary"
              size="small"
              @click="addEditProjectType"
            >添加项目类型</el-button>
          </div>
        </div>

        <!-- 修改合同电子版上传部分 -->
        <div class="contract-upload-section">
          <div class="section-title">合同电子版上传</div>
          <el-upload
            ref="editUpload"
            class="upload-box"
            drag
            :limit="1"
            :http-request="customEditUpload"
            :on-error="handleEditUploadError"
            :on-change="handleEditContractChange"
            :file-list="editFileList"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <!-- <div class="el-upload__tip" slot="tip">只能上传doc/docx文件</div> -->
          </el-upload>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情弹框 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      width="87%"
      title="查看详情"
      custom-class="full-height-dialog"
    >
      <!-- 添加一个用于打印的区域，使用 id 标识 -->
      <div id="printArea" class="dialog-content-wrapper">
        <div class="collapse-header">
          <h3>北仑区传媒中心经营项目立项</h3>
        </div>
        <el-card>
          <div>
            <div class="detail-content">
              <div class="contract-no">合同编号：{{ projectDetail.no }}</div>
              <el-form label-width="100px" class="detail-form">
                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目名称">
                      <el-input
                        v-model="projectDetail.pname"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目采购方式">
                      <el-input
                        v-model="projectDetail.projectFrom"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="客户类型">
                      <el-input
                        v-model="projectDetail.customerType"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户单位">
                      <el-input
                        v-model="projectDetail.customer"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目领域">
                      <el-input
                        v-model="projectDetail.projectArea"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目负责人">
                      <el-input v-model="projectDetail.salesman" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="存量类型">
                      <el-input
                        v-model="projectDetail.stockType"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="执行时间">
                      <el-input
                        v-model="projectDetail.duration"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="项目成本">
                      <el-input
                        v-model="projectDetail.cost"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同金额">
                      <el-input
                        v-model="projectDetail.money"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="实际收入">
                      <el-input v-model="projectDetail.income" disabled>
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否到账">
                      <el-input
                        v-model="projectDetail.isAccount"
                        disabled
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="12">
                    <el-form-item label="到账金额">
                      <el-input
                        v-model="projectDetail.receiveMoney"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目奖励比例">
                      <el-input
                        v-model="projectDetail.manageRate"
                        disabled
                        style="width: 100%"
                      >
                        <template slot="append">%</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="0">
                  <el-col :span="24">
                    <el-form-item label="内容及要求">
                      <el-input
                        v-model="projectDetail.content"
                        type="textarea"
                        :rows="4"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </el-card>

        <el-card style="margin-top: 20px">
          <div>
            <div class="project-type">
              <div class="type-title">项目类型</div>
              <el-table
                :header-cell-style="{ background: '#f5f7fa' }"
                :data="projectDetail.list || []"
                border
                style="width: 100%"
              >
                <el-table-column
                  prop="platform"
                  label="平台产品IP"
                  width="120"
                />
                <el-table-column
                  prop="department"
                  label="执行事业部"
                  width="150"
                />
                <el-table-column
                  prop="content"
                  label="执行内容及要求"
                  width="300"
                  align="center"
                />
                <el-table-column prop="attribute" label="属性" align="center" />
                <el-table-column prop="money" label="金额" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.money || "0" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="estimatedCost"
                  label="成本"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.estimatedCost || "0" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transferCompany"
                  label="划转对象"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.transferCompany || "无" }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="transferMoney"
                  label="划转金额"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ scope.row.transferMoney || "0" }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>

        <!-- <el-card style="margin-top: 20px">
          <div style="border: 2px solid #ebeef5">
            <div class="contract-info">
              <div class="info-item">
                <div class="info-label">合同电子版</div>
                <div class="info-content">
                  <a
                    :href="projectDetail.contractFile"
                    class="download-link"
                    v-if="projectDetail.contractFile"
                    @click.prevent="
                      handleFileDownload(projectDetail.contractFile)
                    "
                  >
                    {{ getFileName(projectDetail.contractFile) }}(点击下载文件)
                  </a>
                  <div class="button-group">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleFileDownload(projectDetail.contractFile)"
                      >下载</el-button
                    >
                    <el-button size="small" @click="handlePreview"
                      >预览</el-button
                    >
                  </div>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">负责人备注</div>
                <div class="info-content">
                  {{ projectDetail.remarks || "" }}
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">项目立项意见</div>
                <div class="info-content">
                  {{ projectDetail.mpSuggest || "" }}
                </div>
              </div>
            </div>
          </div>
        </el-card> -->
        <el-card style="margin-top: 20px">
          <div style="border: 2px solid #ebeef5">
            <div class="contract-info">
              <div class="info-item">
                <div class="info-label">合同电子版</div>
                <div class="info-content">
                  <a
                    v-if="projectDetail.contractFile"
                    :href="projectDetail.contractFile"
                    class="download-link"
                    @click.prevent="
                      handleFileDownload(projectDetail.contractFile)
                    "
                  >
                    {{ getFileName(projectDetail.contractFile) }}(点击下载文件)
                  </a>
                  <div class="button-group">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleFileDownload(projectDetail.contractFile)"
                    >下载</el-button>
                    <el-button
                      size="small"
                      @click="handlePreview"
                    >预览</el-button>
                  </div>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">负责人备注</div>
                <div class="info-content">
                  {{ projectDetail.remarks || "" }}
                </div>
              </div>

              <div class="info-section">
                <div style="border: 1px solid #ccc">
                  <div class="info-row">
                    <div class="info-col">
                      <div
                        class="info-label"
                        style="width: 180px; color: black; font-weight: bold"
                      >
                        项目立项意见
                      </div>
                      <div class="info-content">
                        {{
                          projectDetail.luser
                            ? `${projectDetail.luser}：${
                              projectDetail.lsuggest || ""
                            }`
                            : ""
                        }}
                      </div>
                    </div>
                    <!-- <div class="info-col">
                      <div class="info-label">项目立项人</div>
                      <div class="info-content">
                        {{ projectDetail.luser || "" }}
                      </div>
                    </div> -->
                  </div>
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row full-width">
                    <div class="info-label">完成概述</div>
                    <div class="info-content">
                      {{ projectDetail.describe || "" }}
                    </div>
                  </div>

                  <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">结案人</div>
                      <div class="info-content">
                        {{ projectDetail.createName || projectDetail.salesman }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">结案时间</div>
                      <div class="info-content">
                        {{
                          formatCreateTime(projectDetail.endCreateTime) || ""
                        }}
                      </div>
                    </div>
                  </div>
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row full-width">
                    <div class="info-col">
                      <div class="info-label">融合发展事业部意见</div>
                      <div class="info-content">
                        {{
                          projectDetail.rmSuggest
                            ? `${projectDetail.rmUserName}：${
                              projectDetail.rmSuggest || ""
                            }`
                            : ""
                        }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{ formatCreateTime(projectDetail.rmUserTime) || "" }}
                      </div>
                    </div>
                  </div>

                  <!-- <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">审批人</div>
                      <div class="info-content">
                        {{ projectDetail.rmUserName || "" }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{ formatCreateTime(projectDetail.rmUserTime) || "" }}
                      </div>
                    </div>
                  </div> -->
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row three-cols">
                    <div class="info-col">
                      <div class="info-label">项目成本</div>
                      <div class="info-content">
                        {{ projectDetail.cost || "0" }}元
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">项目税金</div>
                      <div class="info-content">
                        {{ projectDetail.tax || "0" }}元
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">项目收入</div>
                      <div class="info-content">
                        {{ projectDetail.income || "0" }}元
                      </div>
                    </div>
                  </div>

                  <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">项目奖励</div>
                      <div class="info-content">
                        {{ projectDetail.manageMoney || "0" }}元
                      </div>
                    </div>
                    <!-- <div class="info-col">
                    <div class="info-label">融合发展事业部意见</div>
                    <div class="info-content">{{ projectDetail.rmSuggest || "" }}</div>
                  </div> -->
                  </div>
                </div>

                <div style="border: 1px solid #ccc">
                  <div class="info-row full-width">
                    <div class="info-col">
                      <div class="info-label">运营中心意见</div>
                      <div class="info-content">
                        {{
                          projectDetail.rcenterSuggest
                            ? `${projectDetail.rcenterUserName}：${
                              projectDetail.rcenterSuggest || ""
                            }`
                            : ""
                        }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{
                          formatCreateTime(projectDetail.rcenterUserTime) || ""
                        }}
                      </div>
                    </div>
                  </div>

                  <!-- <div class="info-row">
                    <div class="info-col">
                      <div class="info-label">审批人</div>
                      <div class="info-content">
                        {{ projectDetail.rcenterUserName || "" }}
                      </div>
                    </div>
                    <div class="info-col">
                      <div class="info-label">审批时间</div>
                      <div class="info-content">
                        {{
                          formatCreateTime(projectDetail.rcenterUserTime) || ""
                        }}
                      </div>
                    </div>
                  </div> -->
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <el-card style="margin-top: 20px">
        <div>
          <div class="timeline-section">
            <el-timeline>
              <el-timeline-item
                :timestamp="formatCreateTime(projectDetail.lTime)"
                placement="top"
                type="primary"
              >
                <el-card>
                  <h4>负责人已填报</h4>
                  <p>操作人：{{ projectDetail.luser }}</p>
                </el-card>
                <!-- <div class="timeline-content">
                <div class="status-text">负责人已填报</div>
                <div class="operator-text">操作人：周永声</div>
              </div> -->
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button v-print="printObj" type="primary">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selContractListApi,
  updateContractByIdApi,
  delContractByIdsApi
} from '@/api/project-management'
import { filePreviewApi, selFileUrlApi } from '@/api/uploadFile'
import { selNewProjectNoApi } from '@/api/project-input'
import {
  selCustomerTypeListApi, // 客户类型列表查询
  selCustomerUnitListApi, // 客户单位列表查询
  selProjectFromListApi, // 项目来源列表查询
  selProjectAreaListApi, // 项目领域列表查询
  selPlatformListApi, // 平台产品列表查询
  selDepartmentListApi, // 执行事业部列表查询
  selProjectTypeListApi // 项目类型列表查询
} from '@/api/basic-data'
import request from '@/utils/requestH2'
import { mapGetters } from 'vuex'
export default {
  name: 'Contract',
  data() {
    return {
      loading: false,
      tableData: [
        {
          id: 1,
          contractNo: '202502051',
          projectName: '宁波市北仑区妇女联合会年度合作协议（妇联）',
          customerUnit: '宁波市北仑区妇女联合会',
          contractAmount: 48000,
          projectManager: '周永声',
          createTime: '2025-02-05 10:56',
          status: '已通过'
        },
        {
          id: 2,
          contractNo: '202501221',
          projectName: '青田年统留守儿童北仑研学活动策划合作协议',
          customerUnit: '宁波北仑圆满旅行社有限责任公司',
          contractAmount: 4000,
          projectManager: '张佳丽',
          createTime: '2025-01-22 00:00',
          status: '已通过'
        },
        {
          id: 3,
          contractNo: '202501202',
          projectName: '教育局少儿春晚合作协议',
          customerUnit: '宁波市北仑区教育局',
          contractAmount: 30000,
          projectManager: '张佳丽',
          createTime: '2025-01-20 14:23',
          status: '已通过'
        },
        {
          id: 4,
          contractNo: '202501172',
          projectName: '白峰街道90、00多村共富记视频策划合作协议',
          customerUnit: '宁波市北仑区人民政府白峰街道办事处',
          contractAmount: 20000,
          projectManager: '郑颖超',
          createTime: '2025-01-17 19:53',
          status: '已通过'
        },
        {
          id: 5,
          contractNo: '202501162',
          projectName: '白峰街道年终节目一起向春天合作协议',
          customerUnit: '宁波市北仑区人民政府白峰街道办事处',
          contractAmount: 149000,
          projectManager: '郑颖超',
          createTime: '2025-01-16 00:00',
          status: '已通过'
        },
        {
          id: 6,
          contractNo: '202501161',
          projectName: '测试项目(勿审/勿删)',
          customerUnit: '测试部门',
          contractAmount: 1,
          projectManager: '周洪涛',
          createTime: '2025-01-16 16:22',
          status: '已通过'
        },
        {
          id: 7,
          contractNo: '202501151',
          projectName: '"情系万家"暖冬行动启动仪式',
          customerUnit: '宁波市北仑区慈善总会',
          contractAmount: 23450,
          projectManager: '吕泽婷',
          createTime: '2025-01-15 00:00',
          status: '已通过'
        },
        {
          id: 8,
          contractNo: '202501091',
          projectName: '测试项目',
          customerUnit: '北仑区传媒中心',
          contractAmount: 0,
          projectManager: '刘岩',
          createTime: '2025-01-09 08:59',
          status: '已通过'
        },
        {
          id: 9,
          contractNo: '202501062',
          projectName: '宁波儿童公园亲子欢乐跑活动',
          customerUnit: '宁波市宝韵艺术培训中心',
          contractAmount: 49000,
          projectManager: '曹跃',
          createTime: '2025-01-06 00:00',
          status: '已通过'
        },
        {
          id: 10,
          contractNo: '202501061',
          projectName: '北仑电厂项目宣传视频',
          customerUnit: '浙江德塔壳特数据技术有限公司',
          contractAmount: 20000,
          projectManager: '吕泽婷',
          createTime: '2025-01-06 00:00',
          status: '已通过'
        }
      ],
      // 合同列表查询
      contractQuery: {
        PType: '', // 项目类型
        page: 1,
        pageSize: 10,
        content: '',
        customer: '',
        dt1: '',
        dt2: '',
        money: '',
        no: '',
        PName: '',
        salesman: '',
        status: 0
      },
      contractList: [], // 合同列表
      total: 0, // 总条数
      isFilterVisible: false,
      dialogVisible: false,
      detailDialogVisible: false,
      editForm: {
        money: '', // 项目金额
        tax: '', // 项目税金
        cost: '', // 项目成本
        income: '', // 项目收入
        managementAward: '', // 项目管理奖
        transferAmount: '' // 划转对象实际金额
      },
      projectDetail: {}, // 项目详情
      // 单据状态列表
      statusList: [
        { label: '全部', value: 0 },
        { label: '已驳回', value: -1 },
        { label: '待审核', value: 1 },
        { label: '已通过', value: 2 }
      ],
      // 客户类型列表参数
      selCustomerTypeListQuery: {
        page: 1,
        pageSize: 99,
        name: ''
      },
      customerUnits: [], // 客户单位列表
      rules: {
        tax: [
          { required: true, message: '请输入项目税金', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '请输入正确的金额格式',
            trigger: 'blur'
          }
        ],
        cost: [
          { required: true, message: '请输入项目成本', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '请输入正确的金额格式',
            trigger: 'blur'
          }
        ],
        income: [
          { required: true, message: '请输入项目收入', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '请输入正确的金额格式',
            trigger: 'blur'
          }
        ],
        managementAward: [
          { required: true, message: '请输入项目管理奖', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '请输入正确的金额格式',
            trigger: 'blur'
          }
        ],
        transferAmount: [
          {
            required: true,
            message: '请输入划转对象实际金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '请输入正确的金额格式',
            trigger: 'blur'
          }
        ]
      },
      selectedRow: [], // 选中的行
      selectedRowId: [], // 选中的行id
      type: 'contract', // 导出类型
      editDialogVisible: false, // 修改弹框显示状态
      editisMediaCenter: false, // 是否是传媒中心
      // 产品平台查询参数
      selPlatformListQuery: {
        page: 1,
        pageSize: 99,
        name: ''
      },
      selectionRow: {}, // 选中的行数据
      editFileList: [], // 修改时的文件列表
      selPlatformLists: [], // 产品平台列表
      selProjectTypeLists: [], // 项目类型列表
      projectTypes: [], // 客户类型列表
      customerUnits: [], // 客户单位列表
      projectFroms: [], // 项目来源列表
      projectAreas: [], // 项目领域列表
      uploadUrl: process.env.VUE_APP_BASE_HOME_API + '/filePreview/uploadFile', // 上传地址
      dateRange: [], // 日期范围
      manageRateOptions: [
        { label: '0%', value: '0' },
        { label: '30%', value: '30' }
      ],
      printObj: {
        id: 'printArea',
        popTitle: '项目查询详情',
        preview: false,
        extraCss: '',
        beforeEntryIframe() {
          try {
            // 获取打印区域
            const printArea = document.getElementById('printArea')
            if (!printArea) return

            // 添加更强制的边框样式
            const styleElement = document.createElement('style')
            styleElement.id = 'print-style-temp'
            styleElement.textContent = `
              /* 整个表格添加边框 */
              #printArea .el-table {
                border: 1px solid #dcdfe6 !important;
                border-collapse: collapse !important;
                border-spacing: 0 !important;
              }
              
              /* 特别强制的单元格边框样式 */
              #printArea .el-table th.el-table__cell,
              #printArea .el-table td.el-table__cell {
                border-top: 1px solid #dcdfe6 !important;
                border-right: 1px solid #dcdfe6 !important;
                border-bottom: 1px solid #dcdfe6 !important;
                border-left: 1px solid #dcdfe6 !important;
              }
              
              /* 确保表头背景色 */
              #printArea .el-table th.el-table__cell {
                background-color: #f5f7fa !important;
              }
              
              /* 移除干扰元素 */
              #printArea .el-table::before,
              #printArea .el-table::after,
              #printArea .el-table .el-table__fixed::before,
              #printArea .el-table .el-table__fixed::after {
                display: none !important;
              }
            `
            document.head.appendChild(styleElement)

            // 处理表格宽度和列组
            const tableNode = printArea.querySelectorAll(
              '.el-table__header,.el-table__body'
            )
            tableNode.forEach((tableItem) => {
              tableItem.style.width = '100%'
              tableItem.style.borderCollapse = 'collapse'
              tableItem.style.borderSpacing = '0'

              // 设置表格列宽比例
              const colgroup = tableItem.querySelector('colgroup')
              if (colgroup) {
                colgroup.innerHTML = ''

                const widths = [
                  '11.2%', // 150px -> 11.2%
                  '14.9%', // 200px -> 14.9%
                  '22.4%', // 300px -> 22.4%
                  '11.2%', // 150px -> 11.2%
                  '8.9%', // 120px -> 8.9%
                  '8.9%', // 120px -> 8.9%
                  '11.2%', // 150px -> 11.2%
                  '11.2%' // 150px -> 11.2%
                ]

                widths.forEach((width) => {
                  const col = document.createElement('col')
                  col.style.width = width
                  colgroup.appendChild(col)
                })
              }
            })

            // 使用setTimeout确保在DOM完全渲染后执行
            setTimeout(() => {
              // 直接操作DOM，强制设置边框样式
              const tables = printArea.querySelectorAll('.el-table')
              tables.forEach((table) => {
                table.style.border = '1px solid #dcdfe6'
                table.style.borderCollapse = 'collapse'
                table.style.borderSpacing = '0'

                // 处理所有单元格
                const cells = table.querySelectorAll(
                  'th.el-table__cell, td.el-table__cell'
                )
                cells.forEach((cell) => {
                  // 为每个边单独设置边框
                  cell.style.setProperty(
                    'border-top',
                    '1px solid #dcdfe6',
                    'important'
                  )
                  cell.style.setProperty(
                    'border-right',
                    '1px solid #dcdfe6',
                    'important'
                  )
                  cell.style.setProperty(
                    'border-bottom',
                    '1px solid #dcdfe6',
                    'important'
                  )
                  cell.style.setProperty(
                    'border-left',
                    '1px solid #dcdfe6',
                    'important'
                  )
                })

                // 表头单元格额外处理
                const headerCells = table.querySelectorAll('th.el-table__cell')
                headerCells.forEach((cell) => {
                  cell.style.setProperty(
                    'background-color',
                    '#f5f7fa',
                    'important'
                  )
                  // 确保内容不会覆盖边框
                  const cellContent = cell.querySelector('.cell')
                  if (cellContent) {
                    cellContent.style.padding = '5px'
                  }
                })
              })
            }, 200) // 增加延迟时间，确保DOM完全渲染
          } catch (error) {
            console.error('Error in beforeEntryIframe:', error)
          }
        },
        closeCallback(vue) {
          console.log('关闭了打印工具')
          // 移除临时样式
          const tempStyle = document.getElementById('print-style-temp')
          if (tempStyle) {
            tempStyle.parentNode.removeChild(tempStyle)
          }
        }
      }
    }
  },
  created() {
    this.selContractList()
    this.selCustomerTypeList() // 客户类型列表
    this.selCustomerUnitList() // 客户单位列表
    this.selProjectFromList() // 项目来源列表
    this.selProjectAreaList() // 项目领域列表
    // this.selNewProjectNo(); // 获取新项目编号
    this.selPlatformList() // 平台产品列表
    this.selDepartmentList() // 执行事业部列表
    this.selProjectTypeList() // 项目类型列表
  },
  computed: {
    ...mapGetters(['isAdministrators'])
  },
  watch: {
    'selectionRow.ptype': {
      async handler(newVal) {
        console.log(newVal)

        if (newVal === '仑传公司') {
          this.selectionRow.no = '' // 清空合同编号
        } else {
          // 如果不是传媒中心，重新获取项目编号
          // try {
          //   const res = await selNewProjectNoApi();
          //   if (res.code === 1) {
          //     this.selectionRow.no = res.data; // 设置项目编号
          //     // this.formData.lppStr[0].projectNo = res.data;
          //   } else {
          //     this.$message.error(res.msg || "获取项目编号失败");
          //   }
          // } catch (error) {
          //   console.error("获取项目编号失败:", error);
          //   this.$message.error("获取项目编号失败");
          // }
          // 使用选中行的no字段
          this.selectionRow.no = this.selectedRow[0]?.no || ''
        }
      },
      immediate: true
    },
    'selectionRow.no': {
      handler(newVal) {
        // 当 no 为空时，清空所有 lppStr 中的 projectNo
        if (!newVal && this.selectionRow.lppStr) {
          this.selectionRow.lppStr.forEach((item) => {
            item.projectNo = ''
          })
        }
        // 当 no 有值时，同步更新所有 lppStr 中的 projectNo
        if (newVal && this.selectionRow.lppStr) {
          this.selectionRow.lppStr.forEach((item) => {
            item.projectNo = newVal
          })
        }
      },
      immediate: true // 立即执行一次
    }
  },

  methods: {
    // 自定义上传
    async customEditUpload(options) {
      try {
        console.log(options)
        const formData = new FormData()
        formData.append('file', options.file)
        const response = await request({
          url: '/filePreview/uploadFile',
          method: 'POST',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        // 处理上传成功的情况
        if (response.code === 1) {
          this.selectionRow.contractFileUrl = response.data
          this.$message.success('上传成功')
          options.onSuccess(response)
        } else {
          // 处理业务逻辑错误
          this.$message.error(response.msg || '上传失败')
          options.onError(new Error(response.msg || '上传失败'))
        }
      } catch (error) {
        // 处理网络错误等异常情况
        console.error('上传失败:', error)
        this.$message.error('文件上传失败，请重试')
        options.onError(error)
      }
    },
    // 查询项目类型列表
    async selProjectTypeList() {
      const res = await selProjectTypeListApi(this.selPlatformListQuery)
      console.log(res)
      this.selProjectTypeLists = res.records
      // this.total = res.total;
    },
    // 执行事业部列表
    async selDepartmentList() {
      const res = await selDepartmentListApi(this.selPlatformListQuery)
      console.log(res)
      this.selDepartmentLists = res.records
      // this.total = res.total;
    },
    // 平台产品列表
    async selPlatformList() {
      const res = await selPlatformListApi(this.selPlatformListQuery)
      console.log(res)
      this.selPlatformLists = res.records
      // this.total = res.total;
    },
    // 获取合同编号
    async selNewProjectNo() {
      const res = await selNewProjectNoApi()
      console.log(res)
      if (res.code === 1) {
        this.selectionRow.no = res.data
        this.selectionRow.lppStr[0].projectNo = res.data
        console.log(this.selectionRow.lppStr[0].projectNo)
      } else {
        this.$message.error(res.msg)
      }
    },

    // 客户类型列表查询
    async selCustomerTypeList() {
      const res = await selCustomerTypeListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.projectTypes = res.records
    },
    // 客户单位列表查询
    async selCustomerUnitList() {
      const res = await selCustomerUnitListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.customerUnits = res.records
    },
    // 项目来源列表查询
    async selProjectFromList() {
      const res = await selProjectFromListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.projectFroms = res.records
    },
    // 项目领域列表查询
    async selProjectAreaList() {
      const res = await selProjectAreaListApi(this.selCustomerTypeListQuery)
      console.log(res)
      this.projectAreas = res.records
    },
    // 导出excel
    async handleExportExcel() {
      console.log('导出excel')
      let loading = null
      try {
        await this.$confirm('此操作将导出所有项目信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 显示loading
        loading = this.$loading({
          lock: true,
          text: '正在导出数据,请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const res = await filePreviewApi(this.type)
        console.log(res)
        if (res.code === 1 && res.data) {
          // 创建a标签下载
          const link = document.createElement('a')
          link.href = res.data
          link.download = '项目信息导出.xlsx'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.$message.success('导出成功')
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        // console.error("导出错误:", error);
        // this.$message.error("导出失败");
      } finally {
        // 关闭loading
        if (loading) {
          loading.close()
        }
      }
    },
    // 项目状态改变
    handleStatusChange(val) {
      console.log(val)
      if (val === '') {
        this.contractQuery.status = 0
      }
      this.selContractList()
    },
    // 获取合同列表
    async selContractList() {
      this.loading = true
      try {
        const res = await selContractListApi(this.contractQuery)
        this.contractList = res.records
        this.total = res.total
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$message.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },
    // 删除选中行
    handleDeleteSelected() {
      if (this.selectedRowId.length === 0) {
        this.$message.warning('请先选择要删除的项目')
        return
      }
      this.$confirm('此操作将永久删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await delContractByIdsApi(this.selectedRowId)
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.selectedRowId = []
            this.selContractList()
          } else {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        })
    },
    handleQuery() {
      this.contractQuery.page = 1
      this.selContractList()
    },
    resetQuery() {
      this.dateRange = [] // 清空日期选择器
      this.contractQuery = {
        page: 1,
        pageSize: 10,
        content: '',
        customer: '',
        dt1: '',
        dt2: '',
        money: '',
        no: '',
        PName: '',
        salesman: '',
        status: 0
      }
      this.selContractList()
    },
    // 查看
    handleView(row) {
      this.detailDialogVisible = true
      this.projectDetail = row
      console.log(this.projectDetail)
    },
    // 修改提交
    handleSubmit() {
      this.$refs.editForm.validate(async(valid) => {
        if (valid) {
          try {
            // 这里调用修改接口
            // const res = await updateContractApi(this.editForm)
            // if (res.code === 200) {
            this.$message.success('修改成功')
            this.dialogVisible = false
            this.selContractList() // 刷新列表
            // }
          } catch (error) {
            console.error('修改失败:', error)
            this.$message.error('修改失败，请重试')
          }
        }
      })
    },
    // 获取文件名
    getFileName(url) {
      if (!url) return ''
      // 截取_后面的部分作为文件名
      console.log(url.split('_').pop())
      return url.split('_').pop()
    },
    // 处理文件下载
    handleFileDownload(url) {
      if (!url) {
        this.$message.warning('文件链接不存在')
        return
      }

      // 拼接完整的下载地址
      // const baseUrl = "http://192.168.11.22:38085";
      const baseUrl = 'http://192.168.11.2:8081'
      const fullUrl = `${baseUrl}${url}`

      // 获取文件名 - 截取_后面的部分
      const fileName = url.split('_').pop()
      console.log(fullUrl)

      try {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = fullUrl
        link.setAttribute('download', fileName) // 使用新的文件名
        document.body.appendChild(link)

        link.click()

        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      }
    },
    // 项目类型改变
    handleProjectTypeChange() {
      console.log(val)
      this.selContractList()
    },
    // 处理文件预览
    async handlePreview() {
      if (!this.projectDetail.contractFile) {
        this.$message.warning('文件链接不存在')
        return
      }
      try {
        // 获取预览链接
        const res = await selFileUrlApi(this.projectDetail.contractFile)
        console.log(res)
        if (res.code === 1 && res.data) {
          // 在新窗口中打开预览链接
          window.open(res.data, '_blank')
        } else {
          this.$message.error(res.msg || '获取预览链接失败')
        }
      } catch (error) {
        console.error('预览失败:', error)
        this.$message.error('预览失败，请重试')
      }
    },
    // 下载文件
    handleDownload(row) {
      if (!row.contractFile) return
      window.open(process.env.VUE_APP_BASE_API + row.contractFile)
    },
    // 分页
    handleSizeChange(val) {
      this.contractQuery.pageSize = val
      this.selContractList()
    },
    // 当前页
    handleCurrentChange(val) {
      this.contractQuery.page = val
      this.selContractList()
    },
    // 表格选择行变化
    handleSelectionChange(selection) {
      console.log(selection)

      this.selectedRowId = selection.map((item) => item.id)
      if (selection.list && Array.isArray(selection.list)) {
        selection.lppStr = selection.list.map((item) => ({
          platform: item.platform || '',
          department: item.department || '',
          content: item.content || '',
          attribute: item.attribute || '',
          money: Number(item.money || 0),
          estimatedCost: Number(item.estimatedCost || 0),
          projectIP: item.projectIP || '',
          projectNo: item.projectNo || ''
        }))
      } // 只取第一个选中的行
      console.log(selection)
      // this.selectedRow = selection.length ? selection[0] : null;
      this.selectedRow = selection
      console.log(this.selectedRow)
    },
    // 封装获取项目状态
    getProjectStatus(status) {
      if (status === null || status === undefined) return ''

      const statusNum = Number(status)
      if (statusNum >= 4) {
        return '已通过'
      } else if (statusNum === 1) {
        return '待审核'
      } else if (statusNum === -1) {
        return '已驳回'
      }
      return ''
    },
    // 封装获取项目状态类型
    getProjectStatusType(status) {
      if (status === null || status === undefined) return ''

      const statusNum = Number(status)
      if (statusNum >= 4) {
        return 'success' // 绿色
      } else if (statusNum === 1) {
        return 'warning' // 黄色
      } else if (statusNum === -1) {
        return 'danger' // 红色
      }
      return 'info' // 默认灰色
    },
    // 点击修改按钮
    handleEdit() {
      console.log(this.selectedRow)
      if (this.selectedRow.length === 0) {
        this.$message.warning('请选择要修改的项目')
        return
      }
      if (this.selectedRow.length > 1) {
        this.$message.warning('请选择单条合同')
        return
      }

      // 深拷贝选中的数据
      const rowData = JSON.parse(JSON.stringify(this.selectedRow[0]))

      // 保存ID
      this.id = rowData.id // 保存ID用于更新操作

      // 处理日期范围
      if (rowData.duration) {
        try {
          const [startDate, endDate] = rowData.duration.split('至')
          rowData.duration = [startDate, endDate]
          this.editdurationForSubmit = `${startDate}至${endDate}`
        } catch (error) {
          console.error('日期处理错误:', error)
          this.editdurationForSubmit = rowData.duration
        }
      }

      // 设置编辑数据
      this.selectionRow = {
        ...rowData,
        manageRate: String(rowData.manageRate) + '%', // 添加百分号
        lppStr: Array.isArray(rowData.list)
          ? rowData.list.map((item) => ({
            platform: item.platform || '',
            department: item.department || '',
            content: item.content || '',
            attribute: item.attribute || '',
            money: Number(item.money || 0),
            estimatedCost: Number(item.estimatedCost || 0), // 添加Number转换
            projectIP: item.projectIP || '',
            projectNo: item.projectNo || ''
          }))
          : []
      }

      // 如果有合同文件，设置文件列表
      if (rowData.contractFile) {
        this.editFileList = [
          {
            name: rowData.contractFile.split('_').pop(), // 获取文件名
            url: rowData.contractFile
          }
        ]
      } else {
        this.editFileList = []
      }

      this.editDialogVisible = true
    },
    // 执行时间改变处理
    handleEditDurationChange(val) {
      if (!val || val.length !== 2) return

      const formatDate = (date) => {
        const d = new Date(date)
        const year = d.getFullYear()
        const month = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      }

      const startDate = formatDate(val[0])
      const endDate = formatDate(val[1])
      this.editdurationForSubmit = `${startDate}至${endDate}`
    },
    // 修改提交
    async handleEditSubmit() {
      try {
        // 构造提交数据
        const submitData = {
          contractFileUrl: this.selectionRow.contractFileUrl,
          createName: this.selectionRow.createName,
          customer: this.selectionRow.customer,
          customerType: this.selectionRow.customerType,
          duration: this.editdurationForSubmit, // 处理后的duration
          executionFee: Number(this.selectionRow.executionFee || 0),
          isImportant: this.selectionRow.isImportant || '0',
          lppStr: this.selectionRow.lppStr.map((item) => ({
            attribute: item.attribute || '',
            content: item.content || '',
            department: item.department || '',
            estimatedCost: Number(item.estimatedCost || 0),
            money: Number(item.money || 0),
            platform: item.platform || '',
            projectIP: item.projectIP || '',
            projectNo: item.projectNo || ''
          })),
          money: Number(this.selectionRow.money || 0),
          no: this.selectionRow.no,
          pname: this.selectionRow.pname,
          ptype: this.selectionRow.ptype,
          salesman: this.selectionRow.salesman,
          stockType: this.selectionRow.stockType,
          projectFrom: this.selectionRow.projectFrom,
          projectArea: this.selectionRow.projectArea,
          manageRate: this.selectionRow.manageRate
            ? String(this.selectionRow.manageRate).replace('%', '')
            : 0
        }

        // 检查项目采购方式是否为空
        if (!submitData.projectFrom || submitData.projectFrom === '') {
          // 如果为空，删除该字段，不传递给后端
          delete submitData.projectFrom
        }

        const res = await updateContractByIdApi(submitData, this.id)
        if (res.code === 1) {
          this.$message.success('修改成功')
          this.editDialogVisible = false
          this.editFileList = []
          this.selContractList() // 刷新列表
        } else {
          this.$message.error(res.msg || '修改失败')
        }
      } catch (error) {
        console.error('修改失败:', error)
        this.$message.error('表单验证失败，请检查必填项')
      }
    },
    // 修改时添加项目类型
    addEditProjectType() {
      this.selectionRow.lppStr = this.selectionRow.lppStr || []
      this.selectionRow.lppStr.push({
        platform: '',
        department: '',
        content: '',
        attribute: '',
        money: '',
        estimatedCost: '',
        projectNo: this.selectionRow.no
      })
    },

    // 修改时删除项目类型
    removeEditProjectType(index) {
      this.selectionRow.lppStr.splice(index, 1)
    },

    // 修改时的文件上传成功处理
    // handleEditUploadSuccess(response, file) {
    //   console.log(response, file);
    //   if (response.code === 1) {
    //     this.selectionRow.contractFileUrl = response.data;
    //     this.editFileList = [
    //       {
    //         name: file.name,
    //         url: response.data,
    //       },
    //     ];
    //     this.$message.success("文件上传成功");
    //   } else {
    //     this.$message.error(response.msg || "文件上传失败");
    //   }
    // },

    // 修改时的文件上传错误处理
    handleEditUploadError(error) {
      console.error('上传失败:', error)
      this.$message.error('文件上传失败，请重试')
    },

    // 修改时的文件改变处理
    handleEditContractChange(file, fileList) {
      // 将fileList的最后一个元素赋值给this.editFileList
      this.editFileList = fileList.slice(-1)
    },

    // 修改时的文件上传前处理
    beforeEditUpload(file) {
      const isDoc =
        file.type === 'application/msword' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      if (!isDoc) {
        this.$message.error('只能上传 Word 文档!')
        return false
      }
      return true
    },

    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 处理日期变化
    handleDateChange(val) {
      if (val) {
        const formatDate = (date) => {
          const d = new Date(date)
          const year = d.getFullYear()
          const month = String(d.getMonth() + 1).padStart(2, '0')
          const day = String(d.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }
        console.log(val)
        // 设置时间戳
        this.contractQuery.dt1 = formatDate(val[0])
        this.contractQuery.dt2 = formatDate(val[1])
      } else {
        // 清空时间
        this.contractQuery.dt1 = ''
        this.contractQuery.dt2 = ''
      }
      // 立即调用查询接口
      this.selContractList()
    },
    // 处理失焦事件
    handleEditManageRateBlur(e) {
      const inputValue = e.target.value
      if (inputValue) {
        // 移除百分号和空格
        const value = String(inputValue).replace(/%|\s/g, '')

        if (!isNaN(value)) {
          // 创建新选项
          const newOption = {
            label: `${value}%`,
            value: String(value) // 确保值是字符串
          }

          // 检查是否已存在该选项
          if (
            !this.manageRateOptions.some((item) => item.value === String(value))
          ) {
            this.manageRateOptions.push(newOption)
          }

          // 设置选中值为字符串
          this.selectionRow.manageRate = String(value)
        }
      }
    },

    // 处理选择改变
    handleEditManageRateChange(val) {
      if (val) {
        // 移除百分号并确保是字符串
        const value = String(val).replace(/%/g, '')
        this.selectionRow.manageRate = String(value)
      }
    },
    // 打印预览方法
    handlePrint() {
      if (this.selectedRow.length === 0) {
        this.$message.warning('请选择要打印的项目')
        return
      }
      if (this.selectedRow.length > 1) {
        this.$message.warning('请选择单条记录打印')
        return
      }
      // 打开详情弹窗
      this.handleView(this.selectedRow[0])
    }
    // 修改打印方法
    // handlePrintDetail() {
    //   try {
    //     // 使用全局的 jQuery (通过 window.jQuery 或 window.$)
    //     window.jQuery("#printArea").print({
    //       title: "",
    //       stylesheet: null,
    //       deferred: window.jQuery.Deferred().done(function () {
    //         console.log("打印完成");
    //       }),
    //     });
    //   } catch (error) {
    //     console.error("打印失败:", error);
    //     this.$message.error("打印失败，请重试");
    //   }
    // },
    // 处理打印
    // handlePrint() {
    //   // 确保有详情视图的ID作为打印区域
    //   if (!this.detailDialogVisible) {
    //     this.$message.warning("请先查看合同详情再打印");
    //     return;
    //   }

    //   // 调用打印方法
    //   this.$print(this.printObj);
    // },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.operation-container {
  margin-bottom: 20px;
  .el-button {
    margin-right: 10px;
  }
}

.search-wrapper {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  flex-wrap: nowrap;
  gap: 20px; /* 添加统一的间距 */
  margin-bottom: 15px;
}

:deep(.el-form-item) {
  margin-right: 15px;
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  color: #606266;
  float: none;
  line-height: 1;
  padding: 0 8px 0 0;
}

:deep(.el-form-item__content) {
  width: 180px;
  margin-left: 0 !important;
  line-height: 1;
}

:deep(.el-input),
:deep(.el-select) {
  width: 100%;
}

/* 项目类型部分 */
.project-type-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 12px;
  margin-bottom: 20px;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 18px;
    background-color: #1e6ced;
    border-radius: 2px;
  }
}

/* 弹窗样式 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-table .el-input) {
  width: 100%;
}

:deep(.el-table .el-select) {
  width: 100%;
}

/* 上传部分 */
.contract-upload-section {
  margin: 20px 0;

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #303133;
  }

  .upload-box {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    text-align: center;
    padding: 20px;
    background-color: #fafafa;
  }
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
  margin-top: 10px;

  em {
    color: #409eff;
    font-style: normal;
  }
}

/* 详情内容样式 */
.detail-content {
  background: #fff;

  .contract-no {
    color: #1b86ee;
    font-size: 16px;
    margin: 20px;
  }
}

/* 项目类型表格样式 */
.project-type {
  margin-top: 20px;

  .type-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 20px;
    padding-left: 10px;
    border-left: 4px solid #409eff;
  }

  :deep(.el-table) {
    th {
      background-color: #f5f7fa;
      color: #606266;
      padding: 8px 0;
      font-weight: normal;
    }

    td {
      padding: 8px;
      color: #606266;
    }
  }
}

/* 滚动条样式 */
.dialog-content-wrapper {
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f7fa;
  }
}

/* 表格内容样式 */
.el-table .cell {
  white-space: nowrap;
}

/* 按钮样式 */
.el-button--text {
  padding: 0;
  margin: 0;
}

/* 标题头部样式 */
.collapse-header {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #303133;

  .view-btn {
    color: #409eff;
    font-size: 14px;
    cursor: pointer;
  }
}

.contract-info {
  // margin-top: 40px;
  // border: 2px solid #ebeef5;
  border-radius: 4px;

  .info-item {
    display: flex;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      width: 130px;
      padding: 12px;
      background-color: #f5f7fa;
      color: #606266;
      font-size: 14px;
      border-right: 1px solid #ebeef5;
    }

    .info-content {
      flex: 1;
      padding: 12px;
      min-height: 44px;
      display: flex;
      align-items: center;
      color: #606266;
      font-size: 14px;

      &:has(.download-link) {
        justify-content: space-between;
      }

      .download-link {
        color: #409eff;
        text-decoration: none;

        &:hover {
          text-decoration: underline;
        }
      }

      .button-group {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}

.info-section {
  // padding: 20px;
  background: #fff;

  .info-row {
    display: flex;
    margin-bottom: 1px;

    &.full-width {
      .info-label {
        width: 180px;
        color: black;
        font-weight: bold;
      }
      .info-content {
        flex: 1;
        color: black;
      }
    }

    &.three-cols {
      .info-col {
        flex: 1;
        margin-right: 1px;
        &:last-child {
          margin-right: 0;
        }
      }
    }

    .info-col {
      display: flex;
      flex: 1;
      margin-right: 1px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .info-label {
    width: 100px;
    // padding: 12px 20px;
    padding: 12px;
    background-color: #f5f7fa;
    color: black;
    font-size: 14px;
    border: 1px solid #ebeef5;
    display: flex;
    align-items: center;
  }

  .info-content {
    padding: 12px 20px;
    min-height: 44px;
    border: 1px solid #ebeef5;
    border-left: none;
    display: flex;
    align-items: center;
    color: black;
    font-size: 14px;
    flex: 1;
  }
}

/* 添加打印样式 */
@media print {
  .el-dialog__header,
  .el-dialog__footer {
    display: none !important;
  }

  .dialog-content-wrapper {
    padding: 0 !important;
  }
}
</style>
